package com.glela.controller;

import java.util.ArrayList;
import java.util.List;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glela.common.constant.CommonConstants;
import com.glela.common.model.ProductTag;
import com.glela.common.util.DateUtil;
import com.glela.common.util.NumberUtil;
import com.glela.goods.mapper.*;
import com.glela.goods.model.*;
import com.glela.goods.model.request.ShoppingCartRequest;
import com.glela.goods.model.vo.ShoppingCartVo;
import com.glela.goods.model.vo.goods.GoodsVo;
import com.glela.goods.model.vo.inventory.DynamicInventoryVo;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.goods.service.ShoppingCartService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.model.request.RequestPageBaseModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 购物车
 * @author liujie
 * @2016年10月20日
 */
@Controller
@RequestMapping("shoppingCart")
public class ShoppingCartController {
	private static Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);

	@Autowired
	private ShoppingCartService	shoppingCartService;
	@Autowired
	private UserService			userService;
	@Autowired
	private GoodsService		goodsService;


	/**
	 * <dl>
	 * <dt>商品添加到购物车</dt>
	 * TODO 存在事务问题
	 * </dl>
	 * @param requestObj
	 * @return ResponseEntity<?>
	 * @author zls
	 */

	@Autowired
	private InventoryMapper inventoryMapper;

	@Autowired
	private LimitTimeSaleDetailMapper limitTimeSaleDetailMapper;

	@Autowired
	private ShoppingCartMapper shoppingCartMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	
	
	@Autowired
	private ProductMapper productMapper;
	
	
	@Autowired
	private GoodsMapper   goodsMapper;
	
	@Autowired
	private GoodsNavigateMapper  goodsNavigateMapper;
	
	@Autowired
	private InventoryService  inventoryService;
	
	
	@RequestMapping(value = "/addShoppingCart", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addShoppingCart(@RequestBody ShoppingCartRequest requestObj) {
		try {
			//			if (ParameterUtils.validParams(requestObj.getUserId(), requestObj.getGoodsId(), requestObj.getSpecInfo(), requestObj.getStoreId(), requestObj.getProductNum())) {
			//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			//			}
			//			Inventory inventory = inventoryService.selectInventoryByGoodsStoreIdSpecInfo(requestObj.getGoodsId(), requestObj.getStoreId(), requestObj.getSpecInfo());
			//			if (requestObj.getInventoryNum() <= 0) {
			//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20409), HttpStatus.OK);
			//			}
			if (ParameterUtils.validParams(requestObj.getUserId(), requestObj.getGoodId(), requestObj.getProductId(), requestObj.getInventoryId(), requestObj.getStoreId(), requestObj.getProductNum())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			GoodsVo goodsVo = goodsService.selectGoodsById(requestObj.getGoodId(), 0, 0);
			if (goodsVo != null && goodsVo.getAscription() > 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20390), HttpStatus.OK);
			}
			//			ShoppingCart shoppingCart = new ShoppingCart();
			//			shoppingCart.setUserId(requestObj.getUserId());
			//			shoppingCart.setGoodId(inventory.getGoodId());
			//			shoppingCart.setProductId(inventory.getProductId());
			//			shoppingCart.setInventoryId(inventory.getId());
			//			shoppingCart.setStoreId(inventory.getStoreId());
			//			shoppingCart.setProductNum(requestObj.getProductNum());
			
			//TODO 查询当前用户购物车此商品（由于限制条件不足，可能会导致有多条返回值）
			ShoppingCart shoppingCart = shoppingCartService.selectByUserInventoryId(requestObj.getUserId(), requestObj.getInventoryId());
			int result = 0;
			if (shoppingCart == null) {//不存在，直接添加到购物车
				result = shoppingCartService.insertSelective(requestObj);
			} else {//存在，累加更新
				shoppingCart.setProductNum(shoppingCart.getProductNum() + requestObj.getProductNum());//累加数量
				shoppingCart.setTalentSerialId(requestObj.getTalentSerialId());
				shoppingCart.setTalentShareGoodId(requestObj.getTalentShareGoodId());
				shoppingCart.setTalentId(requestObj.getTalentId());
				result = shoppingCartService.updateByPrimaryKeySelective(shoppingCart);
			}
			if (result == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/updateShoppingCart", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateShoppingCart(@RequestBody ShoppingCart requestObj) {
		try {
			if (ParameterUtils.validParams(requestObj.getId(), requestObj.getProductNum())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int result = shoppingCartService.updateByPrimaryKeySelective(requestObj);
			if (result == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/deleteShoppingCartById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> deleteShoppingCartById(@RequestBody ShoppingCart requestObj) {
		try {
			if (ParameterUtils.validParams(requestObj.getId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int result = shoppingCartService.deleteByPrimaryKey(requestObj.getId());
			if (result == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/selectMoreInfoByUserIdPageDouble", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectMoreInfoByUserIdPageDouble(@RequestBody RequestPageBaseModel requestPageBaseModel) {
		try {
			if (ParameterUtils.validParams(requestPageBaseModel.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			requestPageBaseModel.setPageSize(50);
			List<ShoppingCartVo> shoppingCartList = shoppingCartService
					.selectMoreInfoByUserIdPage(requestPageBaseModel);
			//遍历商品 修改规格显示图片
			for(ShoppingCartVo v:shoppingCartList){
			     long ProID=v.getProductId();
			    String imgPath=shoppingCartService.selectImgPathByProductID(ProID);
			    if(StringUtils.isNotBlank(imgPath)){
			    	v.setImagePath(imgPath);
			    }
			}
			int i = 0;
			for (ShoppingCartVo shoppingCartVo : shoppingCartList) {
				if (shoppingCartVo.getGoodsType().intValue() != 0) {
					break;
				}
				i++;
			}
			List<List<ShoppingCartVo>> list = new ArrayList<List<ShoppingCartVo>>();
			if (i > 0) {
				if (i == shoppingCartList.size()) {
					if (shoppingCartList.size() > 0) {
						list.add(shoppingCartList);
					}
				} else {
					User user = userService.selectRecommendFromByUserId(requestPageBaseModel.getUserId());
					List<ShoppingCartVo> list1 = new ArrayList<ShoppingCartVo>(shoppingCartList.subList(0, i));
					List<ShoppingCartVo> list2 = new ArrayList<ShoppingCartVo>(
							shoppingCartList.subList(i, shoppingCartList.size()));
					list.add(list1);
					list2.get(0).setStoreName(user.getNickName() != null ? user.getNickName() : "");
					list.add(list2);
				}
			} else if (i == 0) {
				if (shoppingCartList.size() > 0) {
					User user = userService.selectRecommendFromByUserId(requestPageBaseModel.getUserId());
					shoppingCartList.get(0).setStoreName(user.getNickName() != null ? user.getNickName() : "");
					list.add(shoppingCartList);
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
			// PageInfo<ShoppingCartVo> pageInfo = new
			// PageInfo<ShoppingCartVo>(shoppingCartList);
			// return new ResponseEntity<>(new ResponseResultModel<>(new
			// ResponsePageModel<ShoppingCartVo>((int)pageInfo.getTotal(),
			// requestPageBaseModel.getPageSize().intValue(),
			// requestPageBaseModel.getPageNum().intValue()
			// , shoppingCartList)),HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/********************************************
	 * 
	 * <dl>
	 * <dt>获取购物车列表</dt>
	 * </dl>
	 * 
	 * @return ResponseEntity<?>
	 * @author gwq
	 * @date 2017年7月21日 13:44:05
	 * 
	 ********************************************/
	@RequestMapping(value = "/selectMoreInfoByUserIdPage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectMoreInfoByUserIdPage(@RequestBody RequestPageBaseModel requestPageBaseModel) {
		try {
			if (ParameterUtils.validParams(requestPageBaseModel.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<ShoppingCartVo> shoppingCartList = shoppingCartService
					.selectMoreInfoByUserIdPage(requestPageBaseModel);
			//遍历商品 修改规格显示图片
			for(ShoppingCartVo v:shoppingCartList){
			     long ProID=v.getProductId();
			    String imgPath=shoppingCartService.selectImgPathByProductID(ProID);
			    if(StringUtils.isNotBlank(imgPath)){
			    	v.setImagePath(imgPath);
			    }
			}
			PageInfo<ShoppingCartVo> pageInfo = new PageInfo<ShoppingCartVo>(shoppingCartList);
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<ShoppingCartVo>(
					(int) pageInfo.getTotal(), requestPageBaseModel.getPageSize().intValue(),
					requestPageBaseModel.getPageNum().intValue(), shoppingCartList)), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/addGouCart", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> addGouCart(@RequestBody ShoppingCartRequest gouCart) {
		try {
			if (ParameterUtils.validParams(gouCart.getUserId(), gouCart.getGoodId(), gouCart.getProductId(),
					gouCart.getInventoryId(), gouCart.getProductNum())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if( gouCart.getStoreId() == null) {
				gouCart.setStoreId(14);
			}
			GoodsVo goodsVo = goodsService.selectGoodsById(gouCart.getGoodId(), 0, 0);
			int public_user_id = baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
			if (goodsVo != null && goodsVo.getAscription() > 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20390), HttpStatus.OK);
			}
			if(goodsVo != null && goodsVo.getGoodsType() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20808), HttpStatus.OK);
			}
			Inventory inventory = inventoryMapper.selectByPrimaryKey(gouCart.getInventoryId());
			if (inventory == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20409), HttpStatus.OK);
			}
			if (inventory.getInventoryNum() < 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20409), HttpStatus.OK);
			}
			if(goodsVo.getCanShoppingCart() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20415), HttpStatus.OK);
			}
			if(goodsVo.getSalesType() == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20416), HttpStatus.OK);
			}
			
			if(goodsVo.getIsOpenGoods() == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20419), HttpStatus.OK);
			}
			if(goodsVo.getCanShoppingCart() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20420), HttpStatus.OK);
			}
			//如果不允许添加C店商品至购物车，则这个地方进行判断提示给客户端，目前暂时不进行判断
			gouCart.setStoreId(inventory.getStoreId());
			// 获取该用户针对本次分时抢购已经购买该产品的数量，用来限制用户最大购买数量
			Map<String, Object> map = new HashMap<String, Object>();
			// 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
			map.put("sku_no", gouCart.getProductId());
			map.put("current_time", new Date());
			LimitTimeSaleDetail limitTimeSaleDetail = limitTimeSaleDetailMapper.selectByProductId(map);
			if (limitTimeSaleDetail != null) {// 说明当前时间，该产品为分时抢购产品
				// 判断库存： 如果当前商品，存在于当前时间点的分时抢购活动中，需要计算分时抢购库存剩余，如果剩余小于1 ，则返回提示信息，
				long sale_id = limitTimeSaleDetail.getLimitTimeSaleId();// 获取当前产品的分时抢购ID，用来计算当前用户的购买数量
				if (limitTimeSaleDetail.getSkuCount() < 1 || inventory.getInventoryNum() < 1) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20409), HttpStatus.OK);
				}

				// 如果分时抢购库存大于1 ， 那么判断当前用户之前是否分时抢购过该产品，是否超过了该分时抢购活动针对每个用户的限购数量
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("userId", gouCart.getUserId());// 用户ID
				paramMap.put("limitTimeSaleId", sale_id);// 分时抢购ID
				paramMap.put("productId", gouCart.getProductId());
				Long count = shoppingCartMapper.selectOrderDetailCount(paramMap);
				long purchase = limitTimeSaleDetail.getProductSalePrice();
				if (count != null && count >= limitTimeSaleDetail.getUserSkuCount()) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20413), HttpStatus.OK);
				}
				gouCart.setSalePrice(purchase);
			} else {
				if (inventory.getInventoryNum() < 1) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20409), HttpStatus.OK);
				}
				
				User recommentUser = userService.selectRecommendFromByUserId(gouCart.getUserId());
				if(recommentUser == null) {
					recommentUser = userMapper.selectByPrimaryKey(Long.valueOf(public_user_id));
				}
				if (recommentUser.getRoleId() < 3) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20414), HttpStatus.OK);
				}
				if (recommentUser.getId() == public_user_id) {// 推荐人为：校妆姐姐
					gouCart.setSalePrice(inventory.getXzSalePrice());
				} else {// 推荐人为：一般店主
					gouCart.setSalePrice(inventory.getSalePrice());
				}
			}
			//ShoppingCart shoppingCart = shoppingCartService.selectByUserInventoryId(gouCart.getUserId(),					gouCart.getInventoryId());
			//public ShoppingCart selectByUserProductId(@Param("userId") Long userId,@Param("productId") Long productId)
			List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserProductId(gouCart.getUserId(),gouCart.getProductId(),1l);
			int result = 0;
			if (shoppingCarts == null || shoppingCarts.size() == 0) {
				List<ShoppingCart> shoppingCartsCountList = shoppingCartMapper.selectByUserProductId(gouCart.getUserId(),gouCart.getProductId(),null);
				if(shoppingCartsCountList != null && shoppingCartsCountList.size() > CommonConstants.SHOPPING_CART_PAGE_SIZE) {
					//C20391
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20391), HttpStatus.OK);
				}
				gouCart.setCreateTime(DateUtil.toString(new Date()));
				gouCart.setAvailable(1);
				if(gouCart.getProductNum() < 1) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20392), HttpStatus.OK);
				}
				result = shoppingCartService.insertSelective(gouCart);
			} else if(shoppingCarts.size() > 1){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}else {
				ShoppingCart shoppingCart = shoppingCarts.get(0);
				//下面方法计算库存，与上面的 inventoryMapper.selectByPrimaryKey(gouCart.getInventoryId()) 这个方法不同，该方法考虑了分时抢购库存。
				DynamicInventoryVo dynamicInventory = inventoryService.findDynaByProductId(gouCart.getProductId());  
				if(dynamicInventory == null) {
					
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30116), HttpStatus.OK);
				}
				
				if( (shoppingCart.getProductNum() + gouCart.getProductNum() ) <= 0  ) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
				}
				
				if( (shoppingCart.getProductNum() + gouCart.getProductNum() ) >  dynamicInventory.getInventoryNumAvl() ) {
					logger.error("添加购物车错误 ，已添加了" + shoppingCart.getProductNum()  + "个, 库存剩余" +  dynamicInventory.getInventoryNumAvl() + "个, 无法添加");
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30116), HttpStatus.OK);
				}
				int updateShoppingCartProductCount = gouCart.getProductNum() + shoppingCart.getProductNum();
				if(updateShoppingCartProductCount < 1) {
					logger.error("添加购物车错误  更新时异常：" + shoppingCart.getProductNum()  + "+" + gouCart.getProductNum() + "个, 小于1");
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20417), HttpStatus.OK);
				}
				shoppingCart.setAvailable(1);
				shoppingCart.setProductNum(updateShoppingCartProductCount);
				shoppingCart.setTalentSerialId(gouCart.getTalentSerialId());
				shoppingCart.setTalentShareGoodId(gouCart.getTalentShareGoodId());
				shoppingCart.setTalentId(gouCart.getTalentId());
				shoppingCart.setSalePrice(gouCart.getSalePrice());
				shoppingCart.setUpdateTime(DateUtil.toString(new Date()));
				result = shoppingCartService.updateByPrimaryKeySelective(shoppingCart);
			}
			if (result == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("添加购物车失败，{}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/clearGouCart", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> clearGouCart(@RequestBody ShoppingCartRequest gouCart) {
		try {
			if (ParameterUtils.validParams(gouCart.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			try {
				shoppingCartService.deleteShopppingCart(gouCart.getUserId(), gouCart.getCartId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}catch (Exception e) {
				logger.error("删除购物车错误 : {}", e);
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("删除清除购物车失败，{}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}

	}

	@RequestMapping(value = "/getGouCart", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getGouCart(@RequestBody ShoppingCartRequest gouCart) {
		Map<String,Object > returnMap = new HashMap<String,Object>();
		if (ParameterUtils.validParams(gouCart.getUserId())) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		//需求后期修改，购物车不分页，限制最多添加99个SKU
		gouCart.setPageNumber(1);
		gouCart.setPageSize(CommonConstants.SHOPPING_CART_PAGE_SIZE);
		// 实时判断当前用户推荐人，用来防止之前加入购物车的时候，推荐人和当前推荐人不一致的时候，对价格产生的影响
		User recommentUser = userService.selectRecommendFromByUserId(gouCart.getUserId());
		int public_user_id = baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
		if(recommentUser == null) {
			recommentUser = userMapper.selectByPrimaryKey(Long.valueOf(public_user_id));
		}
		ShoppingCart cart = new ShoppingCart();
		cart.setUserId(gouCart.getUserId());
		//cart.setProductId(gouCart.getProductId());
		// 分页处理
		PageHelper.startPage(gouCart.getPageNumber(), gouCart.getPageSize());
		Page<ShoppingCart> page = (Page<ShoppingCart>) shoppingCartMapper.selectAll(cart);
		//****************************
		returnMap.put("pageNumber", gouCart.getPageNumber());
		returnMap.put("pageSize", gouCart.getPageSize());
		returnMap.put("isHasNextPage", page.toPageInfo().isHasNextPage());
		returnMap.put("productCount", page.getTotal());
		returnMap.put("storeName", "小铺来了");
//		if(recommentUser != null) {
//			returnMap.put("storeName", recommentUser.getNickName() + "的小铺");
//		}else {
//			returnMap.put("storeName", "校妆姐姐" + "的小铺");
//		}
		//***************************
		ShoppingCartVo vo;
		List<ShoppingCartVo> returnList = new ArrayList<ShoppingCartVo>();
		List<ShoppingCartVo> availableList = new ArrayList<ShoppingCartVo>();
		for (int i = 0; page != null && i < page.size(); i++) {
			ShoppingCart c = page.get(i);
			vo = new ShoppingCartVo();
			/********************************
			 * 添加公共显示信息： 名称，图片，规格 数量
			 *************************************************************/
			
			
		    vo.setId(c.getId()); 
		    vo.setInventoryId(c.getInventoryId());
		    vo.setGoodsName("");
		    vo.setProductNum(c.getProductNum());
		    vo.setSpecName("");
		    vo.setProductTags(goodsService.getGoodsTag(c.getGoodId(), c.getProductId()));
		    vo.setGoodId(c.getGoodId());
		    vo.setProductId(c.getProductId());
		    vo.setUserId(c.getUserId());
		    vo.setAvailable(c.getAvailable());
		    vo.setAvailableMsg(c.getAvailableMsg());
		    Product product = productMapper.selectProductByIdNoStatus(c.getProductId());
		    if(product == null) {
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
			}
		    Goods goods = goodsMapper.selectGoodsByIdForAll(product.getGoodId());
		    
		    if(goods == null) {
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
				
			}
			
		    
			
			if(!StringUtils.isBlank(product.getSpecInfo())  && product.getSpecInfo().indexOf("|") > 0) {
				String spec_id = null;
				//取规格图片
				if(product.getSpecInfo().split("\\|") != null && product.getSpecInfo().split("\\|").length > 0) {
					spec_id = product.getSpecInfo().split("\\|")[0];
				}
				String specImage = null;
				if(!StringUtils.isBlank(spec_id)) {
					specImage = goodsMapper.getSpecificationImagesPath(goods.getId(),Integer.valueOf(spec_id));
				}
				if(!StringUtils.isBlank(specImage)) {
					vo.setImagePath(specImage);
				}else {
					 List<GoodsNavigate>   navigateList =     goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
					 if(navigateList != null && navigateList.size() < 0) {
						 vo.setImagePath(navigateList.get(0).getNavigateImage());
					 }
				}
			}else {
				 List<GoodsNavigate>   navigateList =     goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
				 if(navigateList != null && navigateList.size() < 0) {
					 vo.setImagePath(navigateList.get(0).getNavigateImage());
				 }
			}
			
            vo.setGoodsName(goods.getName());
            vo.setSpecName(product.getSpecName());
			vo.setGoodsType(goods.getGoodsType());
			vo.setBrandId(goods.getBrandId());
			vo.setGoodsName(goods.getName());
			
			if(product.getStatus() == 0) { //若需要对GOODS有效性进行判断，在这里添加
				vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
			}
			
		   //失效商品产进行再次计算
		   if(c.getAvailable() == 0) {
			   availableList.add(vo);
			   c.setAvailable(0);
				c.setAvailableMsg(c.getAvailableMsg());
				shoppingCartMapper.updateByPrimaryKey(c);
			   continue ;
		   }
		   if(goods.getGoodsType() == 0) {
			    vo.setAvailable(0);
				vo.setAvailableMsg("商品已下架");
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				availableList.add(vo);
				continue ;
				
		   }
			/********************************
			 * 添加公共显示信息： 名称，图片，规格 结束
			 ********************************************************/

			/*************************
			 * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品）
			 *********************************/
			Inventory inventory = inventoryMapper.selectAllInventoryByProductId(c.getProductId());
			/*************************
			 * 取当前产品的库存 通过库存记录取出产品价格（非抢购商品） 结束
			 *********************************/
			long cart_sale_price = c.getSalePrice();
			/**************************根据下架状态设置产品失效**************************************/
			//跟小朱确认，规格产品表中的这个状态用来标识 ，是否下架
			Goods haveGoods = goodsMapper.selectGoodsById(product.getGoodId());
			if(haveGoods == null || product.getStatus() == 0) {
				c.setAvailable(0);
				c.setAvailableMsg("商品已下架");
				shoppingCartMapper.updateByPrimaryKey(c);
				vo.setSalePrice(0);
				vo.setShowPrice("0");
				vo.setAvailable(0);
				//vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
				vo.setAvailableMsg("商品已下架");
				availableList.add(vo);
				continue ;
			};
			
			/**************************根据下架状态设置产品失效  结束**********************************/
			// 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
			// 判断是不是分时抢购（进行中的商品）
			Map<String, Object> map = new HashMap<String, Object>();

			map.put("sku_no", c.getProductId());
			map.put("current_time", new Date());
			LimitTimeSaleDetail limitTimeSaleDetail = limitTimeSaleDetailMapper.selectByProductId(map);
			if (limitTimeSaleDetail != null) {// 该商品当前在分时抢购中
				// 抢购中的商品取抢购价，如果当前抢购价格跟购物车中存的价格相比有了降价需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
				long sortPrice = limitTimeSaleDetail.getProductSalePrice() - cart_sale_price;
				/******************************根据产品库存计算购物车商品是否失效************************************************/
				int inventoryNumber = (limitTimeSaleDetail.getSkuCount() > inventory.getInventoryNum()) ? inventory.getInventoryNum() : limitTimeSaleDetail.getSkuCount();
				if(inventoryNumber < 1) {
					c.setAvailable(0);
					c.setAvailableMsg("商品已经卖光了");
					shoppingCartMapper.updateByPrimaryKey(c);
					vo.setSalePrice(0);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					//vo.setAvailableMsg("价格当前价格上涨了: " + sortPrice + " 元, 失效！");
					vo.setAvailableMsg("商品已经卖光了");
					availableList.add(vo);
					continue ;
				}
				
				
				
				/******************************根据产品库存计算购物车商品是否失效  结束*************************************************/
				
				if (sortPrice > 0) {// 涨价了,购物车该条记录失效
					c.setAvailable(0);
					c.setAvailableMsg("商品已不能购买");
					shoppingCartMapper.updateByPrimaryKey(c);
					// 产品经理确认，失效产品不显示价格
					vo.setSalePrice(0);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					vo.setAvailableMsg("商品已不能购买");
					availableList.add(vo);
					continue ;
				} else {
					// 计算降价标签
					if (sortPrice != 0) {
						vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))));
					}
					vo.setSalePrice(limitTimeSaleDetail.getProductSalePrice());
					vo.setShowPrice(String.valueOf(NumberUtil.getMoney(limitTimeSaleDetail.getProductSalePrice())));
					//c.setSalePrice(limitTimeSaleDetail.getProductSalePrice());//系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
					//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					// 添加： 特惠标签
				}
				//这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
				if(inventoryNumber < c.getProductNum()) {
					vo.setDescPrice("库存小于购买数量  ");
				}
				
				
				
			} else {// 不是分时抢购商品
				
				/******************************根据产品库存计算购物车商品是否失效************************************************/
				if(inventory.getInventoryNum() < 1) {
					c.setAvailable(0);
					c.setAvailableMsg("商品已经卖光了");
					shoppingCartMapper.updateByPrimaryKey(c);
					vo.setSalePrice(0);
					vo.setShowPrice("0");
					vo.setAvailable(0);
					vo.setAvailableMsg("商品已经卖光了");
					availableList.add(vo);
					continue ;
				}
				/******************************根据产品库存计算购物车商品是否失效 结束************************************************/
				if (recommentUser.getId() == public_user_id) {// 当前用户，为校妆姐姐下面的会员
					Long sortPrice = inventory.getXzSalePrice() - cart_sale_price;
					if (sortPrice > 0) {// 涨价了,购物车该条记录失效
						c.setAvailable(0);
						c.setAvailableMsg("商品已不能购买");
						shoppingCartMapper.updateByPrimaryKey(c);
						// 产品经理确认，失效产品不显示价格
						vo.setSalePrice(0);
						vo.setShowPrice("0");
						vo.setAvailable(0);
						vo.setAvailableMsg("商品已不能购买");
					} else {// 降价了
						// 计算降价标签
						if (sortPrice != 0) {
							//NumberUtil.getFloatPrice(inventory.getXzSalePrice())
							Long _sortPrice = Math.abs(sortPrice);
							vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(_sortPrice.intValue())));
						}
						vo.setSalePrice(inventory.getXzSalePrice());
						vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getXzSalePrice())));
						//c.setSalePrice(inventory.getXzSalePrice()); ////系统判断出来当前产品降价后只在前端体现，暂不更新购物车中的价格
						//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					}
				} else {// 当前用户，为一般店主下面的用户
					Long sortPrice = inventory.getSalePrice() - cart_sale_price;
					if (sortPrice > 0) {// 涨价了,购物车该条记录失效
						c.setAvailable(0);
						c.setAvailableMsg("商品已不能购买");
						shoppingCartMapper.updateByPrimaryKey(c);
						// 产品经理确认，失效产品不显示价格
						vo.setSalePrice(0);
						vo.setShowPrice("0");
						vo.setAvailable(0);
						vo.setAvailableMsg("商品已不能购买");
					} else {// 降价了
						// 计算降价标签
						if (sortPrice != 0) {
							vo.setDescPrice("已降 ￥ " + String.valueOf(NumberUtil.getMoney(Math.abs(sortPrice))) );
						}
						vo.setSalePrice(inventory.getSalePrice());
						vo.setShowPrice(String.valueOf(NumberUtil.getMoney(inventory.getSalePrice())));
						//c.setSalePrice(inventory.getSalePrice());
						//shoppingCartMapper.updateByPrimaryKey(c); // 将最新价格更新到购物车中
					}
				}
				
				//这里会覆盖掉原有的降价提示，因为这个提示比降价提示重要，会影响到下单
				if(inventory.getInventoryNum() < c.getProductNum()) {
					vo.setDescPrice("库存小于购买数量  ");
				}
				
				// 判断是不是分时抢购 （预热中的商品），预热中的商品显示(根据店主，校妆姐姐身份显示价格)，加上预热标记，
				// 如果非预热中的，也是根据（一般店主，校妆姐姐）取价格，如果取到的当前价格跟购物车中存的价格相比有了降价
				// 需加上降价标记，如果价格上涨，则加上失效标识，失效原因：商品价格上涨，更新购物车这两个字段。
				if(vo.getAvailable() != 0 ) {//当产品失效的时候，不进行预热判断
					Map<String, Object> warmupParamMap = new HashMap<String, Object>();
					// 先判断该规格商品（当前时间）是否存在分时抢购活动中，如果存在则忽略身份，直接显示抢购价
					Date nextDay = DateUtil.parse(DateUtil.getNextDate() + " 00:00:00");
					warmupParamMap.put("sku_no", c.getProductId());
					warmupParamMap.put("currentEndTime", nextDay);
					warmupParamMap.put("currentTime", new Date());
					String warmupBegin = limitTimeSaleDetailMapper.selectWarmupByProduct(warmupParamMap);
					if (!StringUtils.isBlank(warmupBegin)) {// 该商品为：预热中商品，按角色
						Date begin_date = DateUtil.parse(warmupBegin);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(begin_date);
						int month = calendar.get(Calendar.MONTH) + 1;
						int day = calendar.get(Calendar.DAY_OF_MONTH);
						int hour = calendar.get(Calendar.HOUR_OF_DAY);
						vo.setWarmupTitle(month + "月" + day + "日  " + hour + " 开始");
						vo.setWarmupTag(new ProductTag("#ff4b7a","预热"));
					}
				}
			}
			if(vo.getAvailable() == 0) {
				availableList.add(vo);
			}else {
				returnList.add(vo);
			}
			
		}
		returnList.addAll(availableList);
		returnMap.put("productList", returnList);
		
		return new ResponseEntity<>(new ResponseResultModel<>(returnMap), HttpStatus.OK);
	}
	/********************************************
	 *
	 * <dl>
	 * <dt>获取购物车列表（新）</dt>
	 * </dl>
	 *
	 * @return ResponseEntity<?>
	 * @author zhangrenjie
	 * @date 2017年10月21日 13:44:05
	 *
	 ********************************************/
	@RequestMapping(value = "/getGouCartNew", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getGouCartNew(@RequestBody ShoppingCartRequest gouCart) {
		try {
			if (ParameterUtils.validParams(gouCart.getUserId())) {
                return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
            }
			Map<String, Object> returnMap ;
			BaseRestrictions restrictions = baseRestrictionsService.getBaseRestrictionsForCache("GOUCART_VERSION");
			if (null != restrictions) {
				if (restrictions.getName().equals("old")) {//无活动
					returnMap = this.shoppingCartService.getShoppingCartSimplify(gouCart);
				}else{
					returnMap = this.shoppingCartService.getShoppingCart(gouCart);
				}
			}else{
				returnMap = this.shoppingCartService.getShoppingCart(gouCart);
			}
//			//带活动标签的接口
//			Map<String, Object> returnMap = this.shoppingCartService.getShoppingCart(gouCart);
			//不带活动标签接口（精简版）
//			Map<String, Object> returnMap = this.shoppingCartService.getShoppingCartSimplify(gouCart);
			return new ResponseEntity<>(new ResponseResultModel<>(returnMap), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询购物车失败，{}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/getGouCartProductCount", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getGouCartProductCount(@RequestBody ShoppingCartRequest gouCart) {
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			
			if(gouCart.getUserId() == null || gouCart.getUserId() == 0) {
				map.put("shoppingCartCount", 0);
			}else {
				ShoppingCart cart = new ShoppingCart();
				cart.setUserId(gouCart.getUserId());
				List<ShoppingCart> list = shoppingCartMapper.selectAll(cart);
				if(list == null || list.size() == 0) {
					map.put("shoppingCartCount", 0);
				}else {
					map.put("shoppingCartCount", list.size());
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		}catch(Exception e) {
			logger.error("查询购物车数量失败，{}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		
	}
	
	@RequestMapping("/selected")
	public @ResponseBody   ResponseEntity<?> selected(@RequestBody ShoppingCartRequest gouCart) {
		try {
//			if(ParameterUtils.validParams(gouCart.getAllSelect())) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
//			}
			
//			if(CommonConstants.SHOPPING_CART_PRODUCT_SINGER_SELECTED == gouCart.getAllSelect()) {
//				if (ParameterUtils.validParams(gouCart.getUserId(), gouCart.getGoodId(), gouCart.getProductId(),gouCart.getInventoryId())) {
//					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
//				}
//			}else {
//				if (ParameterUtils.validParams(gouCart.getUserId())) {
//					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
//				}
//			}
			Map<String,Object> dataMap = shoppingCartService.updateSelected(gouCart);
			return new ResponseEntity<>(new ResponseResultModel<>(dataMap), HttpStatus.OK);
		}catch(Exception e) {
			logger.error(" 更新购物车选中状态错误:  {} "  ,e);
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C20000), HttpStatus.OK);
		}
		
	}
	
	
	
}
